package com.asbd.springboot.service;

import cn.hutool.core.util.RandomUtil;
import com.asbd.springboot.entity.User;
import com.asbd.springboot.exception.ServiceException;
import com.asbd.springboot.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 功能：
 * 作者：ASBD
 * 日期：2024/12/7 11:56
 */

@Service
public class UserService {


    @Autowired
    private UserMapper userMapper;

    //新增用户信息
    public void insertUser(User user) {
        userMapper.insertUser(user);
    }

    //根据id修改用户信息
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }

    //根据id删除用户信息
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }

    //批量删除用户信息
    public void batchDeleteUser(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.deleteUser(id);
        }
    }

    //查询全部用户信息
    public List<User> selectAllUser() {
        return userMapper.selectAll();
    }

    //根据Id查询用户信息
    public User selectUserById(Integer id) {
        return userMapper.selectUserById(id);
    }

    //验证用户账户是否合法
    public User login(User user) {
        //根据用户名查询数据库的用户信息
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser == null) {
            //抛出一个自定义的异常
            //throw new ServiceException("账号不存在！");
            throw new ServiceException("用户名或密码错误！");

        }
        if (!user.getPassword().equals(dbUser.getPassword())) {
            throw new ServiceException("用户名或密码错误！");

        }
        return user;
    }


    public User register(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser != null) {
            //抛出一个自定义的异常
            throw new ServiceException("用户名已存在！");
        }
        user.setName(user.getName());
        userMapper.insertUser(user);
        return user;
    }
}